# Copyright (c) 2009 Barry Schwartz
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

#--------------------------------------------------------------------------

import buildtree
import imp
import os

from os.path import abspath, basename, join
from subprocess import Popen, PIPE

from site_utilities import *
config = imp.load_source('config', join('python', 'kt', 'config.py'))

env = Environment()
Export('env')
env.Tool('ocaml')

env['BUILDERS']['SandwichedOutput'] = Builder(action = sandwiched_output_builder)

#--------------------------------------------------------------------------

building_out_of_source = True

Decider('timestamp-newer') # There is some bug making MD5 signatures
                           # unreliable for us.

#--------------------------------------------------------------------------

if os.getenv('TEST_PYCAML'):
    # At the Crud Factory, we develop pycaml in a directory adjacent
    # to this one.
    pycaml_dir   = join(os.getcwdu(), '..', 'pycaml')
    pycaml_flags = ['pycaml' + config.pyver_pack + '.cmxa',
                    '-I', pycaml_dir,
                    '-ccopt', '-L' + pycaml_dir,
                    '-cclib', '-lpycaml' + config.pyver_pack + '_stubs']
else:
    pycaml_dir   = find_package_dir(env, 'pycaml' + config.pyver_pack)
    pycaml_flags = ['-package', 'pycaml' + config.pyver_pack]
Export('pycaml_dir pycaml_flags')

obj_list = []
bin_list = []
plugin_list = []

cmap_list = [join('data', 'Identity-H')]

ant_generic_list = [
    join('texmf', 'ant', 'generic', p) for p in [
        'allib.ant',
        'defines.ant',
        'minimal.ant',
        'page-layout.ant',
        ]
    ]

preprocessor = [
    '-package', 'camlp4',
    '-syntax', 'camlp4o',
    ]
Export('preprocessor')

#--------------------------------------------------------------------------

# You have a choice of arithmetic modules:

#   'Float' : floating point; this is the fastest option, but there
#           may be round-off error.

#   'Gmp' : multiple precision arithmetic using GNU MP; you will need
#           both GNU MP and the 'mlgmp' OCaml package
#           (http://www-verimag.imag.fr/~monniaux/programmes.html.en).

#   'Num' : multiple precision arithmetic using the 'Num' module that
#           is distributed with OCaml. Speed is lower than with the
#           'Gmp' option.

# Putting more than option in this list probably makes sense only if
# you are doing out-of-source builds. In any case, the first entry
# becomes the default kt.
arithmetic_options = ['Float']

for arithmetic_module in arithmetic_options:
    Export('arithmetic_module')

#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    if building_out_of_source:
        build_root = join(abspath('build') + '.' + arithmetic_module.lower())
        src_dir    = abspath(join(build_root, 'src'))
        buildtree.make_build_tree(env, 'src', build_root)
    else:
        build_root = abspath('src')
        src_dir    = build_root

    bin_dir = join(build_root, 'bin')
    if not os.access(bin_dir, os.F_OK):
        Execute(Mkdir(bin_dir))

    plugin_dir = join(build_root, 'plugin')
    if not os.access(plugin_dir, os.F_OK):
        Execute(Mkdir(plugin_dir))

    hyph_dir     = abspath('hyphenation-patterns')
    data_dir     = abspath('data')
    unicode_data = join(data_dir, 'UnicodeData.txt')
    tools_dir    = abspath(join(src_dir, 'Tools'))

    hyph_langs = None           # To use all the hyphenation patterns.
    #hyph_langs = ['esperanto', 'us']  # To select one or more.

    Export('build_root src_dir plugin_dir hyph_dir data_dir ' +
           'unicode_data tools_dir hyph_langs')

    env['OCAMLFLAGS'] = Split('-g -rectypes -w Ae -warn-error A')
    
    camomile_dir = Popen(['ocamlfind', 'query', 'camomile'], stdout = PIPE).communicate()[0].strip()
    env['OCAMLFLAGS'] += ['-I', camomile_dir]

    if 'Gmp' in arithmetic_options:
        gmp_dir = Popen(['ocamlfind', 'query', 'gmp'], stdout = PIPE).communicate()[0].strip()
        env['OCAMLFLAGS'] += ['-I', gmp_dir]

    env['CFLAGS'] = Split(config.CFLAGS + ' ' + config.PIC)

#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    kpathsea_libs = '-lkpathsea'
    Export('kpathsea_libs')

    gen_hyph_table = join(bin_dir, 'kt_GenHyphTable')
    main_program   = join(bin_dir, 'kt.' + arithmetic_module.lower())
    Export('gen_hyph_table main_program')

    (bins, plugins) = SConscript(join(src_dir, 'SConscript'))
    bin_list = bin_list + bins
    plugin_list = plugin_list + plugins

#--------------------------------------------------------------------------

env.Command([join(config.bin_dir, 'kt')],
            [join(config.bin_dir, 'kt.' + arithmetic_options[0].lower())],
            Symlink('$TARGET', '$SOURCE'))

env.Default(bin_list + plugin_list)

env.Install(config.bin_dir, bin_list)
env.Install(config.plugin_dir, plugin_list)
env.Install(config.cmap_dir, cmap_list)
env.Install(config.ant_generic_dir, ant_generic_list)
    
env.Alias('install-bin', config.bin_dir)
env.Alias('install-plugin', config.plugin_dir)
env.Alias('install-cmap', config.cmap_dir)
env.Alias('install-ant-generic', config.ant_generic_dir)
env.Alias('install',
          ['install-bin',
           'install-plugin',
           'install-cmap',
           'install-ant-generic',
           ]
          )

#--------------------------------------------------------------------------

# local variables:
# mode: python
# python-indent: 4
# end:
